//
//  WebData.m
//  Conference
//
//  Created by 陈鑫 on 12-11-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

//请求与获取webservce的值

#import "WebData.h"

#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"
#import "NetContant.h"
#import "Globals.h"
#import "AppDelegate.h"
#import "Member.h"
@interface UIDevice(Private)

-(NSString *)macAddress;

@end

@implementation UIDevice(Private)

-(NSString *)macAddress{
    int                 mib[6];
    
    size_t              len;
    
    char                *buf;
    
    unsigned char       *ptr;
    
    struct if_msghdr    *ifm;
    
    struct sockaddr_dl  *sdl;
    
    
    mib[0] = CTL_NET;
    
    mib[1] = AF_ROUTE;
    
    mib[2] = 0;
    
    mib[3] = AF_LINK;
    
    mib[4] = NET_RT_IFLIST;
    
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        
        printf("Error: if_nametoindex error\n");
        
        return NULL;
        
    }
    
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        
        printf("Error: sysctl, take 1\n");
        
        return NULL;
        
    }
    
    
    if ((buf = malloc(len)) == NULL) {
        
        printf("Could not allocate memory. error!\n");
        
        return NULL;
        
    }
    
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        
        printf("Error: sysctl, take 2");
        
        return NULL;
        
    }
    
    
    ifm = (struct if_msghdr *)buf;
    
    sdl = (struct sockaddr_dl *)(ifm + 1);
    
    ptr = (unsigned char *)LLADDR(sdl);
    
    NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X", 
                           
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    
    free(buf);
    
    
    return outstring;
}

@end

@interface NSString(MD5Addition)

- (NSString *) stringFromMD5;

@end 

@implementation NSString(MD5Addition)

- (NSString *) stringFromMD5{        
    if(self == nil || [self length] == 0)        
        return nil;       
    const char *value = [self UTF8String];        
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, strlen(value), outputBuffer);       
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];  
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){      
        [outputString appendFormat:@"%02x",outputBuffer[count]];    
    }        
    return [outputString autorelease];
}
@end 


@implementation WebData

static WebData *globalInstance=nil;
static NSString * wd_header = @"<?xml version=\"1.0\" encoding=\"utf-8\"?><S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"><S:Header/><S:Body>%@</S:Body></S:Envelope>";
static NSString * wd_server =@"http://app.citssh.com.cn/webservice/ConferenceService.asmx";
static NSString * wd_namespace = @"http://tempuri.org/";

-(id)init{
	if(self =[super init]){
		
        methodUserCheckVersion=@"UserCheck_Version";
        methodGetMemberAlarm  =@"GetMemberAlarm"; 
        methodGetMemberSchedule =@"GetMemberSchedule";
        methodGetMemberScheduleDate = @"GetMemberScheduleDate";
        methodGetNews = @"GetNews";
        methodGetNewsDetail = @"GetNewsDetail";
        methodGetHotelInfo = @"GetHotelInfo";     
        methodGetEleInfo = @"GetEleInfo";
        methodUpdateGps = @"UpdateGps";   
        methodGetActivityPlaceInfo= @"GetActivityPlaceInfo"; 
        methodGetPlaceDetail= @"GetPlaceDetail";	
        methodGetEleSpeakInfo= @"GetEleSpeakInfo";
        methodGetEleSpeakInfoDetail= @"GetEleSpeakInfoDetail";
        methodGetActivities= @"GetActivities";
        methodGetActivitiesDetail= @"GetActivitiesDetail";
        methodGetCustomerInfo= @"GetCustomerInfo";
        methodPutCustomerInfo = @"PutCustomerInfo";
        methodGetFlight = @"GetFlight";
        methodGetFlightDetail=@"GetFlightDetail";
        methodGetRandMember=@"getRandMember";
        methodUpdatePrivacy=@"updatePrivacy";
	}
	return self;
}
+(WebData *)getInstance {
	@synchronized(self){
		if (globalInstance ==nil) {
			globalInstance=[[WebData alloc] init];
		}
	}
	return globalInstance;
}

-(NSString *) getInfo:(NSString *) function parms:(NSDictionary*) parms{
	NSString* stringReply = [self sendRequest:function parms:parms];
	NSString* returnVlaue =[self getReturn:stringReply function:function];
	return returnVlaue;
}

//向webservce发送请求
-(NSString* ) sendRequest:(NSString*) function parms:(NSDictionary*) parms{
	NSMutableString * parmString = [NSMutableString stringWithFormat:@""];
	if(parms !=nil){
		NSArray * keys = [parms allKeys];
		for (NSString* key in keys) {
			[parmString appendString:[NSString stringWithFormat:@"<%@>%@</%@>",key,[parms objectForKey:key],key]];
		}
	}
	
	NSMutableString * soapFunction = [NSMutableString stringWithFormat:@"<%@ xmlns=\"%@\">%@</%@>",function,wd_namespace,parmString,function];
	NSString *soapMessage = [NSString stringWithFormat:wd_header,soapFunction];
	
    soapMessage = [soapMessage stringByReplacingOccurrencesOfString:@"&" withString:@"\\u0026"];
#ifdef WDDEBUG
	NSLog(@"send soap message = %@",soapMessage);
#endif
	
	NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",wd_server]];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[theRequest addValue: [wd_namespace stringByAppendingString:function] forHTTPHeaderField:@"SOAPAction"];
	[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	[theRequest setTimeoutInterval:5];
    
	NSHTTPURLResponse *response=nil;
    NSData *dataReply=nil;
	NSError * error=nil;
	dataReply = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
	
	if(dataReply != nil && error==nil){
		NSString* stringReply = [(NSString *)[[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding] autorelease];
#ifdef WDDEBUG
		NSLog(@"receive soap message = %@",stringReply);
		
#endif	
		return stringReply;
	}else {
		@throw [NSException exceptionWithName:@"connect error" reason:[error localizedDescription] userInfo:error.userInfo];
	}
}
//解析返回值
-(NSString*) getReturn:(NSString*) stringReply function:(NSString *)function{
	NSString * response = [stringReply stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
	NSRange returnStart = [response rangeOfString:[NSString stringWithFormat:@"<%@Result>",function]];
	NSRange returnEnd = [response rangeOfString:[NSString stringWithFormat:@"</%@Result>",function]];
	if(returnStart.location != NSNotFound && returnEnd.location != NSNotFound){
		NSRange returnRange;
		returnRange.location = returnStart.location + returnStart.length;
		returnRange.length = returnEnd.location - returnStart.location - returnStart.length;
		
		NSString * returnstr = [response substringWithRange:returnRange];
		return returnstr;
	}
	
	returnStart = [response rangeOfString:@"<faultstring>"];
	returnEnd = [response rangeOfString:@"</faultstring>"];
	
	if(returnStart.location != NSNotFound && returnEnd.location != NSNotFound){
		NSRange faultRange;
		faultRange.location = returnStart.location + returnStart.length;
		faultRange.length = returnEnd.location - returnStart.location - returnStart.length;
		NSString * returnfault = [response substringWithRange:faultRange];
		@throw [NSException exceptionWithName:@"soap fault err" reason:returnfault userInfo:nil];
	}
	return nil;
}

#pragma mark -#pragma mark Public Methods

//- (NSString *) uniqueDeviceIdentifier{    
//    NSString *macaddress = [[UIDevice currentDevice] macAddress];   
//    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];      
//    NSString *stringToHash = [NSString stringWithFormat:@"%@%@",macaddress,bundleIdentifier];   
//    NSString *uniqueIdentifier = [stringToHash stringFromMD5]; 
//    NSLog(@"uniqueDeviceIdentifier:%@",uniqueIdentifier);
//    return uniqueIdentifier;
//}

- (NSString *) uniqueGlobalDeviceIdentifier{    
    NSString *macaddress = [[UIDevice currentDevice] macAddress];  
    NSString *uniqueIdentifier = [macaddress stringFromMD5];  
    NSLog(@"uniqueGlobalDeviceIdentifier:%@",uniqueIdentifier);
    return uniqueIdentifier;
}



-(NSString *)userCheckVersion:(NSString *)userCode pwd:(NSString *)pwd{

    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
   
       NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:userCode,@"userName",pwd,@"Pwd",
                        [[Globals getInstance] sLanguage],@"Language",nil];
        
       return  [self getInfo:methodUserCheckVersion parms:dic];
    
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];

    }
   
}

-(NSString *)getMemberAlarm{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
       
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.memberId],@"memberId",[[Globals getInstance] sAlarmUpdate],@"preUpdate",
                            [[Globals getInstance] sLanguage],@"Language",nil];
        
        return  [self getInfo:methodGetMemberAlarm parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }


}


-(NSString *)getMemberSchedule:(NSString*)selectDate{

    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",selectDate,@"date",
                            [[Globals getInstance] sLanguage],@"Language",nil];
        
        return  [self getInfo:methodGetMemberSchedule parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }

}

-(NSString *)getNews{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",[[Globals getInstance] sNewsUpdate],@"preUpdate",
                            [[Globals getInstance] sLanguage],@"Language",nil];
        
        return  [self getInfo:methodGetNews parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }

}

-(NSString *)getNewsDetail:(int)newId{

    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",newId],@"newsId",nil];
        
        return  [self getInfo:methodGetNewsDetail parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
}


-(NSString *)getHotelInfo{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.memberId],@"memberID",[[Globals getInstance] sLanguage],@"Language",nil];
        
        return  [self getInfo:methodGetHotelInfo parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    

}

-(NSString *)getEleInfo{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.memberId],@"memberID",[[Globals getInstance] sLanguage],@"Language",nil];
        
        return  [self getInfo:methodGetEleInfo parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
    
}

-(NSString *)updateGps:(NSString *)longitude dimension:(NSString *)dimension{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.memberId],@"memberID",longitude,@"cLongitude",dimension,@"cDimension",nil];
        
        return  [self getInfo:methodUpdateGps parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
    
}

-(NSString *)getActivityPlaceInfo:(NSString *)preDate{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",[[Globals getInstance] sLanguage],@"Language",preDate,@"preDate",nil];
        
        return  [self getInfo:methodGetActivityPlaceInfo parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
    
}

-(NSString *)getPlaceDetail:(int)placesId{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",placesId],@"placesId",nil];
        
        return  [self getInfo:methodGetPlaceDetail parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
    
}

-(NSString *)getEleSpeakInfo:(NSString *)preDate{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",[[Globals getInstance] sLanguage],@"Language",preDate,@"preDate",nil];
        
        return  [self getInfo:methodGetEleSpeakInfoDetail parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
    
}

-(NSString *)getActivities{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",[[Globals getInstance] sLanguage],@"Language",nil];
        
        return  [self getInfo:methodGetActivities parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)getActivitiesDetail:(int)activitiesId{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",activitiesId],@"activitiesId",nil];
        
        return  [self getInfo:methodGetActivitiesDetail parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)getCustomerInfo:(int)messageID{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",messageID],@"customerId",[[Globals getInstance] sLanguage],@"Language",[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",nil];
        
        return  [self getInfo:methodGetCustomerInfo parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)putCustomerInfo:(NSString *)question{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.memberId],@"memberId",[[Globals getInstance] sLanguage],@"Language",[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",question,@"question",nil];
        
        return  [self getInfo:methodPutCustomerInfo parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)getFlight:(NSString *)type preUpdate:(NSString *)preUpdate{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:preUpdate,@"preUpdate",[[Globals getInstance] sLanguage],@"Language",[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",type,@"type",nil];
        
        return  [self getInfo:methodGetFlight parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)getFlightDetail:(NSString *)type _id:(int)_id{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",_id],@"flghtId",type,@"type",nil];
        
        return  [self getInfo:methodGetFlightDetail parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)getRandMember{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[[Globals getInstance] sLanguage],@"Language",[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",nil];
        
        return  [self getInfo:methodGetRandMember parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)getMemberScheduleDate{
    
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[[Globals getInstance] sLanguage],@"Language",[NSString stringWithFormat:@"%d",member.conferenceId],@"conferenceId",nil];
        
        return  [self getInfo:methodGetMemberScheduleDate parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }
    
}

-(NSString *)updatePrivacy:(NSString*)isCheck{
    if (![self isNetworkAvailable]) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
    }
    @try {
        
        Member *member=[(AppDelegate *)[[UIApplication sharedApplication] delegate] userMember];
        
        NSDictionary *dic =[[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%d",member.memberId],@"memberId",isCheck,@"isCheck",nil];
        
        return  [self getInfo:methodUpdatePrivacy parms:dic];
        
        
    }@catch (NSException *exception) {
        return [[NetContant getInstance] NET_CONNECT_FALSE];
        
    }

}
//检查网络是否连通了
-(BOOL)isNetworkAvailable{
    
	if ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus]!=NotReachable) {
		return YES;
	}
	if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] !=NotReachable) {
		return YES;
	}	
	return NO;
	
}



@end

